﻿using System.Text;
using System.Windows;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void SaveExpressionToDataBase()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            if (Globals.pathOfExpressionDatabase == null)
            {
                MessageBox.Show("未找到数据库文件，此功能不可用！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.SubPanel)
            {
                MessageBox.Show("子面板不能存入数据库中！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (curEx is Expressions.BaseText)
            {
                Expressions.BaseText curBt = curEx as Expressions.BaseText;
                if (curBt.IsCollapsed)
                {
                    MessageBox.Show("折叠的标题文本块不能被存入数据库。",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }

            string defKeyWord = null;

            Expressions.BaseText bt = Globals.GetFstBaseText(curEx);
            if (bt != null)
            {
                string source = bt.Text;
                if (IsValidateKeyWord(source))
                {
                    defKeyWord = source;
                }
            }

            Globals.SaveExpressionToDataBase(Globals.selectedEditor.SelectedExpression.XmlData, defKeyWord);
        }

        /// <summary>
        /// 此方法与SaveFileAs文件中的静态方法GetDefFileNameOfEditor(Editor editor)遵守的规则基本一致，
        /// 但在代码中没有长度限制——因为对话框中已经限制了。
        /// 
        /// 句点也不允许！
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private static bool IsValidateKeyWord(string source)
        {
            if (source == null || source.Length <= 0) return false;

            if (source.Contains("\r") == true || source.Contains("\n") == true ||
                source.Contains("\\") == true || source.Contains("/") == true ||
                source.Contains(":") == true || source.Contains("*") == true ||
                source.Contains("?") == true || source.Contains("\"") == true ||
                source.Contains("<") == true || source.Contains(">") == true ||
                source.Contains("|") == true || source.Contains(".") == true)
            {
                return false;
            }

            return true;
        }
    }
}
